<script setup>
import { ref, onMounted, reactive } from 'vue'
import { ElMessageBox, ElMessage } from "element-plus"
import { takeAccessToken } from "@/api/login"
import axios from 'axios'

// 存储用户数据
let allUser = ref([{}])

// 获取用户数据
function getAllAccount(){
  // 从后端请求数据 - 直接获取所有用户
  axios.get('/api/auth/allAccounts', {
    headers:{
      Authorization: `Bearer ${takeAccessToken()}`
    }
  })
  .then(({ data }) => {
    // console.log(data.data)
    allUser.value = [...data.data]
    // console.log(allUser)
  })
  .catch((err) => {
    console.log(err)
  })
}

// 一进入页面就开始加载
onMounted(async () => {

  try{
    getAllAccount()
  } catch (err) {
    console.log(err)
  }

})

// 删除用户
const handleDelete = (user) => {
  const id = user.id

  ElMessageBox.confirm(`确认删除用户吗？删除后无法恢复！`, '警告信息', {
    confirmButtonText: '确认',
    cancelButtonText: '取消'
  })
  .then(() => {
    // 还没有测试
    // 调用删除API，删除用户
    axios.delete(`/api/auth/delete/${id}`, {
      headers:{
        Authorization: `Bearer ${takeAccessToken()}`
      }
    })
    .then(() => {
      ElMessage.success('删除成功')
      getAllAccount()
      // console.log(res)
    })
    .catch((err) => {
      console.log(err)
    })
  })
  .catch((err) => {
    console.log(err)
  })

}

// -----------------------------------------------------------------------------
// 添加用户
const dialogUserForm = ref(false) // 默认是不展示

const userForm = reactive({})

const roles = [
  {
    value: 'man', label: '管理员'
  },
  {
    value: 'stu', label: '学生'
  },
  {
    value: 'doc', label: '校医'
  }
]

const userFormRef = ref(null);

const rules = reactive({
  uid: [
    { required: true, message: '用户账号不能为空', trigger: 'blur' },
    { pattern: /^\d{6,10}$/, message: '用户账号必须是6-10位数字', trigger: 'blur' }
  ],
  role: [
    { required: true, message: '请选择用户角色', trigger: 'blur' }
  ],
  sum: [
    {
      required: true, message: '请输入添加总数', trigger: 'blur'
    }
  ]
});

// 提交创建用户表单
function subUserForm(){
  try{
    // console.log(userForm)
    userFormRef.value.validate((valid) => {
      // 如果不通过就点击提交，报错
      if(!valid){
        ElMessage.warning('非法输入！')
        return
      }
      // 提交后端操作

      axios.post('/api/auth/add', {
        id: userForm.uid,
        role: userForm.role,
        gender: 0,
        username: `abc${userForm.uid}`,
        phone: `138${userForm.uid}`
      }, {
        headers:{
          Authorization: `Bearer ${takeAccessToken()}`
        }
      })
      .then((res) => {
        // console.log(res)
        if(res.data.message === 200){
          ElMessage.success('添加成功')
        } else {
          ElMessage.warning(res.data.message)
        }
        // 隐藏表单
        dialogUserForm.value = false
        // 清空输入
        resetUserForm()
        getAllAccount()
      })
    })
  } catch (err) {
    ElMessage.warning(err.data.message)
    // console.log(err)
  }

}

// 清空输入表单
function resetUserForm(){
  userForm.uid = ''
  userForm.role = ''
  userForm.sum = ''
}

// 批量新增用户
const dialogMoreUserForm = ref(false)

function subMoreUserForm(){
  try{
    // console.log(userForm)
    userFormRef.value.validate((valid) => {
      // 如果不通过就点击提交，报错
      if(!valid){
        ElMessage.warning('非法输入！')
        return
      }
      // 提交后端操作

      axios.post('/api/auth/batchAdd', {
        start: userForm.uid,
        role: userForm.role,
        sum: userForm.sum.toString(),
        gender: 0,
        username: `abc${userForm.uid}`,
        phone: `138${userForm.uid}`
      }, {
        headers:{
          Authorization: `Bearer ${takeAccessToken()}`,
          "Content-Type": 'multipart/form-data',
        }
      })
      .then((res) => {
        // console.log(res)
        if(res.data.message === 200){
          ElMessage.success('添加成功')
        } else {
          ElMessage.warning(res.data.message)
        }
        // 隐藏表单
        dialogMoreUserForm.value = false
        // 清空输入
        resetUserForm()
        getAllAccount()
      })
      .catch((err) => {
        console.log(err)
      })
    })
  } catch (err) {
    ElMessage.warning(err.data.message)
    // console.log(err)
  }
}

</script>

<template>
  <el-card>
    <el-table :data="allUser" style="font-size: 16px" max-height="350">
      <el-table-column prop="id" label="账号"></el-table-column>
      <el-table-column prop="username" label="姓名"></el-table-column>
      <el-table-column prop="gender" label="性别">
        <template v-slot="scope">
          <span>
            {{ scope.row.gender === 0 ? '男' : scope.row.gender === 1 ? '女' : '未登记' }}
          </span>
        </template>
      </el-table-column>
      <el-table-column prop="role" label="角色">
        <template v-slot="scope">
          <span>
            {{ scope.row.role === 'man' ? '管理员' : scope.row.role === 'stu' ? '学生' : scope.row.role === 'doc' ? '校医' : '' }}
        </span>
        </template>
      </el-table-column>
      <el-table-column prop="phone" label="手机"></el-table-column>
      <el-table-column label="操作">
        <template #default="scope">
          <el-button type="danger" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 添加用户 -->
    <el-button type="primary" @click="dialogUserForm = true" class="buttonCss">添加用户</el-button>
    <el-button type="primary" @click="dialogMoreUserForm = true" class="buttonCss">批量添加用户</el-button>

    <!-- 添加用户面板 -->
    <el-dialog title="添加用户" v-model="dialogUserForm" style="margin-top: 188px;width: 50%;">
      <el-form :model="userForm" :rules="rules" ref="userFormRef" label-width="100px" style="margin: 28px 0;">

        <el-form-item label="用户账号" prop="uid">
          <el-input v-model="userForm.uid" autocomplete="off" placeholder="请输入用户账号"></el-input>
        </el-form-item>
        <el-form-item label="用户角色" prop="role">
          <el-select v-model="userForm.role" placeholder="请选择用户角色">
            <el-option
                v-for="role in roles"
                :key="role.value"
                :label="role.label"
                :value="role.value">
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>

      <template v-slot:footer>
        <div class="dialog-footer">
          <el-button @click="dialogUserForm = false">取 消</el-button>
          <el-button type="primary" @click="subUserForm">提 交</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 批量添加用户面板 -->
    <el-dialog title="批量添加用户（适用于批量新增学生）" v-model="dialogMoreUserForm" style="margin-top: 188px;width: 50%">
      <el-form :model="userForm" :rules="rules" ref="userFormRef" label-width="100px" style="margin: 28px 0;">

        <el-form-item label="起始账号" prop="uid">
          <el-input v-model="userForm.uid" autocomplete="off" placeholder="请输入起始账号"></el-input>
        </el-form-item>
        <el-form-item label="添加总数" prop="sum">
          <el-input v-model="userForm.sum" autocomplete="off" placeholder="请输入添加总数"></el-input>
        </el-form-item>
        <el-form-item label="用户角色" prop="role">
          <el-select v-model="userForm.role" placeholder="请选择用户角色">
            <el-option
                v-for="role in roles"
                :key="role.value"
                :label="role.label"
                :value="role.value">
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>

      <template v-slot:footer>
        <div class="dialog-footer">
          <el-button @click="dialogMoreUserForm = false">取 消</el-button>
          <el-button type="primary" @click="subMoreUserForm">提 交</el-button>
        </div>
      </template>
    </el-dialog>

  </el-card>
</template>

<style scoped>
.buttonCss {
  margin-top: 18px;
}
</style>